//
//  AXFHomeViewController.m
//  AIXF
//
//  Created by Macx on 2017/7/9.
//  Copyright © 2017年 Macx. All rights reserved.
//

#import "AXFHomeViewController.h"
#import "AXFTestNetWorkViewController.h"
#import "AXFCollectionViewFlowLayout.h"
#import "AXFHomeCollectionViewCell.h"
#import "AXFHeadView.h"
#import "Constant.h"
#import "AXFHomeSever.h"
#import "AXFHomeCycleImageModel.h"
#import "AXFWebViewController.h"
#import "AXFHomeMiddleModel.h"
#import "AXFHomeViewModel.h"
#import "AXFHomeFirstSellModel.h"
#import "NSAttributedString+Additon.h"
#import "AXFScaniconViewController.h"
#import "AXFCellSelectedTableViewController.h"
#import "AXFSearchViewController.h"
#import "AXFMapViewController.h"
#import "UIView+WP.h"
#import <UIImageView+WebCache.h>
#import "AXFAccountManager.h"
#import "AXFRefreshControl.h"
#import <SVProgressHUD.h>
@interface AXFHomeViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,CAAnimationDelegate>

@property (nonatomic,strong)NSArray <AXFHomeFirstSellModel *>*cellModelArray;

@property (nonatomic,strong)UICollectionView * collectionView;

@property (nonatomic, strong) NSMutableArray *carArray;

@property (nonatomic,strong)AXFRefreshControl *refreshControl;

@end
@implementation AXFHomeViewController

- (NSMutableArray *)carArray {
    if (nil == _carArray) {
        _carArray = [NSMutableArray array];
    }
    
    return _carArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.cellModelArray = [AXFHomeViewModel shared].firstSellModelArray;
    
    [self setupBarItem];
    
    [self setupCollectionView];
    
    [self setupRefreshControl];
   
    [self setupNotification];
    
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:250/255.0 green:203/255.0 blue:61/255.0 alpha:1];
}

- (void)setupRefreshControl
{
    _refreshControl = [[AXFRefreshControl alloc] init];
    
    [_refreshControl addTarget:self action:@selector(refreshData) forControlEvents:UIControlEventValueChanged];
    
    [self.collectionView addSubview:_refreshControl];
}

- (void)setupNotification
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pushFocusWebViewWithToUrl:) name:@"postFocusModel" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pushIconWebViewWithToUrl:) name:@"postIconModel" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiceArray) name:@"postArray" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReceiveIncrementNotification:) name:kIncrementNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReceiveDecrementNotification:) name:kDecrementNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReceiveGoodNumDidChangeNotification:) name:kIncrementGoodsNumNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReceiveNotification) name:@"postNum" object:nil];
    
}

- (void)setupCollectionView
{
    AXFCollectionViewFlowLayout *flowLayout = [AXFCollectionViewFlowLayout new];
    
    UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:flowLayout];
    
    _collectionView = collectionView;
    
    collectionView.backgroundColor = [UIColor lightGrayColor];
    
    [self.view addSubview:collectionView];
    
    [collectionView registerClass:[AXFHomeCollectionViewCell class] forCellWithReuseIdentifier:@"cell"];

    [collectionView registerNib:[UINib nibWithNibName:@"AXFHomeCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"cell"];
    //注册头部视图
    [collectionView registerNib:[UINib nibWithNibName:@"AXFHeadView" bundle:nil]
     forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headView"];
    
    collectionView.dataSource = self;
    
    collectionView.delegate = self;
}

- (void)setupBarItem
{
    //左侧扫一扫
    UIButton *leftButton = [self setupButtonItemWithImageName:@"icon_black_scancode" andTitle:@"扫一扫"];
    [leftButton addTarget:self action:@selector(scnicon) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    //右侧搜索
    UIButton *rightButton = [self setupButtonItemWithImageName:@"icon_search" andTitle:@"搜索"];
    
    [rightButton addTarget:self action:@selector(search) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    //中间地图
    UIButton *capBtn = [self setupTitleView];
    
    [capBtn addTarget:self action:@selector(map) forControlEvents:UIControlEventTouchUpInside];
    
    self.navigationItem.titleView = capBtn;
}

//创建左右两边的barButtonItem
- (UIButton *)setupButtonItemWithImageName:(NSString *)imageName andTitle:(NSString *)title
{

    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
    
    button.frame = CGRectMake(0, 0, 54, 30);
    
    NSAttributedString *attr = [NSAttributedString imageTextWithImage:[UIImage imageNamed:imageName] imageWH:20 title:title fontSize:12 titleColor:[UIColor darkGrayColor] spacing:3];
    
    [button setAttributedTitle:attr forState:UIControlStateNormal];
    
    button.titleLabel.numberOfLines = 0;
    // 设置按钮中的文字居中对齐
    button.titleLabel.textAlignment = NSTextAlignmentCenter;
    
    return button;

    
}
//扫一扫界面按钮
- (void)scnicon
{
    AXFScaniconViewController *vc = [AXFScaniconViewController new];
    
    [self.navigationController pushViewController:vc animated:YES];
}
// 搜索界面按钮
- (void)search
{
    AXFSearchViewController *vc = [AXFSearchViewController new];
    
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)map
{
    AXFMapViewController *vc = [AXFMapViewController new];
    
    [self.navigationController pushViewController:vc animated:YES];
}
//地图定位按钮
- (UIButton *)setupTitleView
{
    UIButton *btn = [[UIButton alloc] init];
    
    [btn setTitle:@"在地图中定位" forState:UIControlStateNormal];
    
    btn.titleLabel.font = [UIFont systemFontOfSize:13];
    
    [btn setImage:[UIImage imageNamed:@"icon_mapmarker_small"] forState:UIControlStateNormal];
    
    btn.frame = CGRectMake(0, 0, 100, 44);
    
    btn.titleLabel.textColor = [UIColor blackColor];
    
    btn.contentEdgeInsets = UIEdgeInsetsMake(0, -5, 0, 0);
    
    btn.imageEdgeInsets = UIEdgeInsetsMake(0, 90, 0, -2.5);
    
    btn.titleEdgeInsets = UIEdgeInsetsMake(0, -btn.currentImage.size.width, 0, btn.currentImage.size.width);
    return btn;
}
- (void)refreshData
{
    CGFloat count = self.cellModelArray.count;
    
    self.cellModelArray = [AXFHomeViewModel shared].firstSellModelArray;
    
    if (self.cellModelArray.count != count)
    {
        [self.refreshControl endRefreshing];
    }
}
- (void)receiceArray
{
    self.cellModelArray = [AXFHomeViewModel shared].firstSellModelArray;
    
    [self.collectionView reloadData];
}

- (void)pushFocusWebViewWithToUrl:(NSNotification *)noti
{
    AXFHomeCycleImageModel *model = noti.object;
    
    AXFWebViewController *vc = [AXFWebViewController new];
    
    vc.urlStr = model.toURL;
    
    [self.navigationController pushViewController:vc animated:YES];
    
}
- (void)pushIconWebViewWithToUrl:(NSNotification *)noti
{
    AXFHomeMiddleModel *model = noti.object;
    
    AXFWebViewController *vc = [AXFWebViewController new];
    
    vc.urlStr = model.customURL;
    
    [self.navigationController pushViewController:vc animated:YES];
    
}
- (void)didReceiveGoodNumDidChangeNotification:(NSNotification *)noti
{
    [self.collectionView reloadData];
}
- (void)didReceiveNotification{
    [SVProgressHUD showImage:[UIImage imageNamed:@"v2_about_logo"] status:@"库存商品不足"];
}


- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


//设置头部文件的大小
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    CGSize size={375,1079};
    return size;
}

// 展示头部视图
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{


    if (kind == UICollectionElementKindSectionHeader)
    {
        AXFHeadView *headerRV = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"headView" forIndexPath:indexPath];
        return headerRV;
        
    }else
    {
        return nil;
        
        
    }
}

// 数据源方法
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.cellModelArray.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    AXFHomeCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    
    AXFHomeFirstSellModel *model = self.cellModelArray[indexPath.item];
    
    cell.model = model;
    
    cell.backgroundColor = [UIColor whiteColor];
    
    return cell;
}


// cell的渐进动画
- (void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath
{
    cell.transform = CGAffineTransformMakeTranslation(0, 80);
    
    [UIView animateWithDuration:0.5 animations:^{
        
        cell.transform = CGAffineTransformIdentity;
        
    } completion:^(BOOL finished) {
        
        
    }];
}

//点击cell实现跳转
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    AXFHomeFirstSellModel *model = self.cellModelArray[indexPath.item];
    
    AXFCellSelectedTableViewController *vc = [AXFCellSelectedTableViewController new];
    
    vc.model = model;
    
    [self.navigationController pushViewController:vc animated:YES];
    
}


//动画
- (void)didReceiveIncrementNotification:(NSNotification *)noti {

    CGPoint startPoint = [noti.userInfo[@"point"] CGPointValue];
 
    AXFHomeFirstSellModel *model = noti.userInfo[@"model"];
    // 只添加一次
    if (![_AXFAccountManager.orderArray containsObject:model]) {
        // 如果数组中没有添加过这个对象就进行添加
        [_AXFAccountManager.orderArray addObject:model];
    }
    CGPoint controlPoint = CGPointMake(startPoint.x + 50, startPoint.y + 50);
    
    CGPoint endPoint = CGPointMake(_ScreenW / 4 * 2.5, _ScreenH - 44);
    
    UIImageView *imgIcon = [[UIImageView alloc] init];

    NSURL *imgUrl = [[NSURL alloc] initWithString:model.img];
    
    imgIcon.frame = CGRectMake(startPoint.x, startPoint.y, 150, 200);
    
    [imgIcon sd_setImageWithURL:imgUrl placeholderImage:[UIImage imageNamed:@"v2_placeholder_full_size"]];

    [kWindow addSubview:imgIcon];
    
    UIBezierPath *bezierPath = [UIBezierPath bezierPath];
    
    [bezierPath moveToPoint:startPoint];
    
    [bezierPath addQuadCurveToPoint:endPoint controlPoint:controlPoint];
    
    // 关键帧动画
    CAKeyframeAnimation *keyFrame = [CAKeyframeAnimation animationWithKeyPath:@"position"];
    
    // 设置路径
    keyFrame.path = bezierPath.CGPath;
    
    // 设置动画时间
    keyFrame.duration = 1;
    
    // 保持动画的最新状态
    keyFrame.removedOnCompletion = NO;
    
    keyFrame.fillMode = kCAFillModeBoth;
    
    CABasicAnimation *scaleFrame = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
    scaleFrame.toValue = @0.3;
    scaleFrame.duration = 1;
    keyFrame.delegate = self;
    [keyFrame setValue:imgIcon forKey:@"imgIcon"];
    [imgIcon.layer addAnimation:keyFrame forKey:nil];
    [imgIcon.layer addAnimation:scaleFrame forKey:nil];
    
    _AXFAccountManager.goodsNum++;

}
- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag {
    
    // 获取传递的redBall, imageView
    UIImageView *imgIcon = [anim valueForKey:@"imgIcon"];
    
    [imgIcon removeFromSuperview];
    
}
- (void)didReceiveDecrementNotification:(NSNotification *)noti
{
    _AXFAccountManager.goodsNum--;
    // 取出模型
    AXFHomeFirstSellModel *model = noti.object;
    
    if (model.count == 0) {
        
        // 需要把这个模型对象从数组中移除
        [_AXFAccountManager.orderArray removeObject:model];
        
    }
  
}

@end
